/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;

import figures.FigureIterator;
import map.DBMap;
import map.Map;
import map.MemMap;
import mapWriters.DBMapWriter;
import mapWriters.MapWriter;

public class DataSource {
	private String host = "192.168.15.2";
	private String database = "celumap";
	private String user = "celumap";
	private String password = "florida";
	private String mapName = "bsas";
	private String version = "0.1";
	private Connection conn = null;
	public Map getMap() {
		return new DBMap(host, database , user, password, mapName, version);
	}
	public String getMapName() {
		return mapName;
	}
	public void setMapName(String mapName) {
		this.mapName = mapName;
	}
	public java.util.Map<String, java.util.List<String>> getMapList(){
		String dsn = "jdbc:mysql://"+host+"/"+database+"?user="+user+"&password="+password;
		java.util.Map<String, java.util.List<String>> r = new HashMap<String, java.util.List<String>>();
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(dsn);
			conn.setAutoCommit(false);
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        } catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Statement s = conn.createStatement();
			s.execute("SELECT map_name, version FROM map");
			ResultSet rs = s.getResultSet();
			while(rs.next()){
				String map_name = rs.getString("map_name");
				String version = rs.getString("version");
				if(!r.containsKey(map_name))
					r.put(map_name, new LinkedList<String>());
				r.get(map_name).add(version);
			}
			rs.close();
			s.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return r;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	public void write(MemMap map) {
		MapWriter w = new DBMapWriter(host, database , user, password, mapName, version);
		FigureIterator i = map.getFigures(null);
		while(i.hasNext())
			w.addFigure(i.next());
		try {
			w.write(null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int getMapId(String mapName, String version){
		int map = -1;
		try {
			Statement s = conn.createStatement();
			s.execute("SELECT map FROM map WHERE map_name='"+mapName+"' and version='"+version+"'");
			ResultSet rs = s.getResultSet();
			if(rs.next()){
				map = rs.getInt("map");
				if(rs.next()){
					rs.close();
				}
			}else{
				Statement u = conn.createStatement();
				u.executeUpdate(
			            "INSERT INTO map (map_name, version) "
			            + "values ('"+mapName+"','0.1')",
			            Statement.RETURN_GENERATED_KEYS);
				map = -1;
				ResultSet rs2 = u.getGeneratedKeys();
			    if (rs2.next()) {
			        map = rs2.getInt(1);
			    }
			    rs2.close();
				u.close();
			}
			rs.close();
			s.close();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}

	public int createVersion(String map_name, String version){
		Statement u;
		int map = -1;
		try {
			u = conn.createStatement();
			u.executeUpdate(
		            "INSERT INTO map (map_name, version) "
		            + "values ('"+map_name+"','"+version+"')",
		            Statement.RETURN_GENERATED_KEYS);
			ResultSet rs2 = u.getGeneratedKeys();
		    if (rs2.next()) {
		        map = rs2.getInt(1);
		    }
		    rs2.close();
			u.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	public void copyMap(int oldMap, int newMap) {
		//TODO
	}
}
